import request from "@/utils/request";
import { ElMessage } from "element-plus";
import { useLoginStore } from "@/stores/login";
const loginStore = useLoginStore()

//const BASE_URL = 'http://106.55.150.129:6096/api'
//const BASE_URL = 'http://127.0.0.1:4523/m1/6113447-5804550-default'
const BASE_URL = 'http://127.0.0.1:5174'

export const reqLoginIn = (data:any) => {
    return request.post<any>(`${BASE_URL}/login`,data)
        .then(response => {
            const { token } = response.token;
            if (token) {
                localStorage.setItem('token', token);
            }
            return response.data;
        })
        .catch(error => {
            if (error.response) {
                const { status, data: errorData } = error.response;
                console.log('请求错误，状态码:', status, '错误信息:', errorData);
            } else if (error.request) {
                console.log('请求发送了但没有收到响应', error.request);
            } else {
                console.log('请求设置时出错', error.message);
            }
            throw error;
        });
}

export const reqCodeCheck = (email: string,code:string) => {
    return request.post<any>(`${BASE_URL}/validCode/check`,{email: email,code:code})
}

export const reqGetCode = (email: string) => {
    return request.post<any>(`${BASE_URL}/validCode`,{email: email})
}

export const reqRegister = (data: any) => {
    return request.post<any>(`${BASE_URL}/register`,data)
        .then(response => {
            return response.data;
        })
        .catch(error => {
            if (error.response) {
                const { status, data: errorData } = error.response;
                if (status === 400) {
                    if (errorData.includes('用户名已存在，请选择其他用户名')) {
                        console.log('用户名已存在，请选择其他用户名');
                        loginStore.isRegisterred = true
                        ElMessage.error('用户名已注册，请登录')
                    } else if (errorData.includes('邮箱已存在，请选择其他邮箱')) {
                        console.log('邮箱已存在，请选择其他邮箱');
                        loginStore.isRegisterred = true
                        ElMessage.error('邮箱已注册，请登录')
                    }
                } else {
                    console.log('请求错误，状态码:', status);
                }
            } else if (error.request) {
                console.log('请求发送了但没有收到响应', error.request);
            } else {
                console.log('请求设置时出错', error.message);
            }
            // 抛出错误，让调用者决定如何处理
            throw error;
        });
}